package com.cqkjxy.commons.services;


import com.cqkjxy.commons.constants.EntityStatus;
import com.cqkjxy.commons.constants.Messages;
import com.cqkjxy.commons.dao.AbstractStatefulEntityDao;
import com.cqkjxy.commons.entities.AbstractStatefulEntity;
import com.cqkjxy.commons.exceptions.FaultError;
import com.cqkjxy.commons.repositories.AbstractStatefulRepository;
import org.springframework.data.domain.Page;

import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true)
public abstract class AbstractStatefulService<T extends AbstractStatefulEntity,
        R extends AbstractStatefulRepository<T>, D extends AbstractStatefulEntityDao<T, R>>
        extends AbstractService<T, R, D> {

    @Transactional(readOnly = false)
    public T changeStatus(int id, int newStatus) {
        assert newStatus == EntityStatus.DISABLED || newStatus == EntityStatus.NORMAL;
        T entityInDb = findOne(id);
        if (entityInDb == null) {
            throw new FaultError(Messages.DATA_NOT_FOUND);
        }

        entityInDb.setStatus(newStatus);
        getDao().createOrSave(entityInDb);

        return entityInDb;
    }

    public Page<T> findEnabledList(int page, int pageSize) {
        return getDao().findAllEnabled(PageRequest.of(page, pageSize));
    }

    public Page<T> findDisabledList(int page, int pageSize) {
        return getDao().findAllDisabled(PageRequest.of(page, pageSize));
    }

    public List<T> findAllEnabled() {
        return getDao().findAllEnabled();
    }

    public List<T> findAllDisabled() {
        return getDao().findAllDisabled();
    }
}
